package com.study.world;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 输出word文件，  有表格，有分页
 */


public class DocUtil {

    //word 分页符
    public  static String PAGE_CHAR = "            <w:p wsp:rsidR=\"00161C0B\" wsp:rsidRPr=\"00BC6A8F\" wsp:rsidRDefault=\"00BC6A8F\">\n" +
            "                <w:pPr>\n" +
            "                    <w:rPr>\n" +
            "                        <w:rFonts w:ascii=\"宋体\" w:h-ansi=\"宋体\" w:cs=\"Arial\"/>\n" +
            "                        <wx:font wx:val=\"宋体\"/>\n" +
            "                        <w:sz w:val=\"24\"/>\n" +
            "                        <w:sz-cs w:val=\"24\"/>\n" +
            "                    </w:rPr>\n" +
            "                </w:pPr>\n" +
            "                <w:r wsp:rsidRPr=\"00BC6A8F\">\n" +
            "                    <w:rPr>\n" +
            "                        <w:rFonts w:ascii=\"宋体\" w:h-ansi=\"宋体\" w:cs=\"Arial\" w:hint=\"fareast\"/>\n" +
            "                        <wx:font wx:val=\"宋体\"/>\n" +
            "                        <w:sz w:val=\"24\"/>\n" +
            "                        <w:sz-cs w:val=\"24\"/>\n" +
            "                    </w:rPr>\n" +
            "                    <w:br w:type=\"page\"/>\n" +
            "                </w:r>\n" +
            "            </w:p>";
    /**
     * 创建word文档
     * @param dataMap 写入文档的内容
     * @param path  ftl文件所在文件夹位置（如：D:/testfile/）
     * @param fileName  ftl文件名
     * @param outPath  word文件输出文件夹位置（如：D:/testfile/）
     * @return outFilePath word文件输出地址（如：D:/testfile/xxx.doc）
     */
    public static String createWord(HashMap<String, Object> dataMap, String path, String fileName,String outPath){
        String outFileName = null;
        Template t=null;
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("UTF-8");
            configuration.setDirectoryForTemplateLoading(new File(path));
            t = configuration.getTemplate(fileName); //文件名

        } catch (IOException e) {
            e.printStackTrace();
        }
        outFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) +".doc";
        String outFilePath = outPath + outFileName;

        //如果文件夹不存在则创建
        File outPathFolder = new File(outPath);
        if(!outPathFolder.exists() && !outPathFolder.isDirectory()){
            outPathFolder.mkdir();
        }

        File outFile = new File(outFilePath);
        Writer out = null;
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8");
            out = new BufferedWriter(outputStreamWriter);
        } catch (Exception e1) {
            e1.printStackTrace();
            return e1.getMessage();
        }
        try {
            t.process(dataMap, out);
            if(out != null){
                out.close();
            }
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outFileName;
    }



    public static void createWord(HashMap<String, Object> dataMap, String path, String fileName, HttpServletResponse response){
        Template t=null;
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("UTF-8");
            configuration.setDirectoryForTemplateLoading(new File(path));
            t = configuration.getTemplate(fileName); //文件名
        } catch (IOException e) {
            e.printStackTrace();
        }
        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        try {
            t.process(dataMap, out);
            if(out != null){
                out.close();
            }
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
    }


    public static void main(String[] args) {
        test1();
    }


    public static void test1(){
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("companyName", "测试商户");
        dataMap.put("webset", "www.baidu.com");
        dataMap.put("createDate", "2021年6月3日");
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        for (int i = 0; i < 50; i++) {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("no", i+1);
            map.put("userName", "张三"+i);
            map.put("uid", "100000"+i);
            map.put("memberId", "100000000"+i);
            map.put("cardNo", "0000");
            list.add(map);
        }

        dataMap.put("list", list);
        dataMap.put("page",PAGE_CHAR);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataMap));
        jsonObject.put("page","");
        HashMap dataMap1 = JSON.parseObject(JSON.toJSONString(jsonObject), HashMap.class);
        List<Map<String,Object>> mapList  = new ArrayList<Map<String,Object>>();
        mapList.add(dataMap);
        mapList.add(dataMap1);
        HashMap<String, Object> exportMap = new HashMap<>();
        exportMap.put("mapList",mapList);
        String createWord = createWord(exportMap, "D:\\test", "2.ftl", "D:/test/");
        System.out.println(createWord);
    }



    public static void test2(){
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("accountName", "基本户");
        dataMap.put("memberName", "新浪测试");
        dataMap.put("companyName", "新浪金融");
        dataMap.put("countDate", "2021年6月3日");
        dataMap.put("openingBalance", "99999.99");
        dataMap.put("closingBalance", "88888.99");
        dataMap.put("invoiceBalance", "7997987");
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        for (int i = 0; i < 5; i++) {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("productName"," 充值-平台方收费"+i);
            map.put("incomeCount", "800"+i);
            map.put("incomeAmount", "100000"+i);
            map.put("outcomeCount", "100000000"+i);
            map.put("outcomeAmount", "0000");
            map.put("feeAmount", "0000");
            list.add(map);
        }

        dataMap.put("list", list);
        dataMap.put("page",PAGE_CHAR);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataMap));
        jsonObject.put("page","");
        jsonObject.put("accountName","分账待结算账户");
        HashMap dataMap1 = JSON.parseObject(JSON.toJSONString(jsonObject), HashMap.class);
        List<Map<String,Object>> mapList  = new ArrayList<Map<String,Object>>();
        mapList.add(dataMap);
        mapList.add(dataMap1);
        HashMap<String, Object> exportMap = new HashMap<>();
        exportMap.put("mapList",mapList);
        String createWord = createWord(exportMap, "D:\\WorkSpace\\work\\ttt", "invoice.ftl", "D:/sinaWorkSpace/work/ttt/");
        System.out.println(createWord);
    }

}